<?php

namespace App\Repositories\Manage;

use App\Models\Member;
use App\Models\MemberLabel;
use App\Models\MemberPark;
use App\Models\WeappScene;

class MemberRepository
{

    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = Member::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("username", "like", "%{$filter['keywords']}%");
            })
            ->when(!empty($filter['username']), function ($query) use ($filter) {
                return $query->where("username", "like", "%{$filter['username']}%");
            })
            ->when(!empty($filter['uid']), function ($query) use ($filter) {
                return $query->where("id", "=", intval($filter['uid']));
            })
            ->when(!empty($filter['mobile']), function ($query) use ($filter) {
                return $query->where("mobile", "like", "%{$filter['mobile']}%");
            })
            ->select(['id', 'username', 'avatar', 'subscribe_scene', 'is_pick', 'integral', 'mobile', 'status', 'reg_time', 'type', 'is_deliver', 'is_replace_order', 'summary'])
            ->orderBy("id", "desc")
            ->paginate($pageSize, ["*"], null, $pageNum);

        foreach ($res as $k => &$v) {
            $v['types'] = MemberLabel::query()->where(['uid' => $v['id']])->pluck("type")->toArray();
            $v['parks'] = (new MemberPark())->setTable("mp")->from("member_park as mp")
                ->join("park as p", "mp.park_id", "=", "p.id")
                ->where("mp.uid", $v['id'])
                ->pluck("p.title");

            if (!checkIsSuper(UID) && strlen($v['username'] ?? 0) > 0) {
                $v['mobile'] = phoneReplace($v['mobile']);
                $v['username'] = cut_str($v['username'] ?? "", 1, 0) . "***";
            }

            if ($v['subscribe_scene']) {
                $v['subscribe_scene_title'] = WeappScene::query()->where(['code' => $v['subscribe_scene']])->value("title");
            }
        }

        return filterPaginateData($res->toArray());
    }

    public function getOne($id = 0)
    {
        $res = Member::query()->where(['id' => intval($id)])->first();
        if ($res['id']) {
            $res['type'] = MemberLabel::query()->where(['uid' => $res['id']])->pluck("type")->toArray();
            $res['park_id'] = MemberPark::query()->where(['uid' => $res['id']])->pluck("park_id")->toArray();
            /*if ($res['is_pick'] == 1) {
                $res['is_deliver'] = 2;//分拣员
            }*/
        }

        //查看来源
        if ($res['subscribe_scene']) {
            $res['subscribe_scene_title'] = WeappScene::query()->where(['code' => $res['subscribe_scene']])->value("title");
        }

        return $res;
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            Member::where("id", $id)->update($data);
            return $id;
        } else {
            return Member::create($data)->id;
        }
    }

    /**
     * 批量删除
     * @param null $ids
     */
    public function batchDelete($ids = null)
    {
        if (intval($ids)) {
            Member::where(['id' => $ids])->delete();
        } else {
            Member::whereIn("id", $ids)->delete();
        }
        return retSuc([], "删除成功");
    }

    /**
     * 更新积分
     * @param $data
     */
    public function updateIntegral($data)
    {
        $id = intval($data['id']);
        if (!$id) return retFail("参数错误");

        $type = intval($data['integralType']);
        $integral = intval($data['integral']);
        if (!is_numeric($integral) || $integral <= 0)
            return retFail("积分错误");

        switch ($type) {
            case 1: //增加
                Member::where("id", $id)->increment("integral", abs($integral));
                break;
            case 2: //减少
                $integral_1 = Member::query()->where("id", $id)->value("integral");
                if ($integral_1 < $integral) {
                    return retFail("积分不足");
                }
                Member::where("id", $id)->decrement("integral", $integral);
                break;
            default:
                return retFail("参数错误");
                break;
        }

        //增加/减少日志
        return retSuc([], ($type == 1 ? '添加' : '减少') . "成功");
    }

    /**
     * 更新会员标签
     * @param int $uid
     * @param array $type
     */
    public function updateType(int $uid = 0, $type = [])
    {
        if (!$uid)
            return false;

        MemberLabel::query()->where(['uid' => $uid])->delete();
        $data = [];
        foreach ($type as $k => $v) {
            $data[] = [
                'uid' => $uid,
                'type' => $v,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
            ];
        }
        MemberLabel::insert($data);

        return true;
    }

}
